package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.Constant;
import com.recharge.common.util.RedisUtil;
import com.recharge.common.util.http.HttpUtil;
import com.recharge.core.entity.CardVoucherEntity;
import com.recharge.core.mapper.CardVoucherMapper;
import com.recharge.domain.query.CardVoucherQueryDO;
import com.recharge.domain.vo.*;
import com.recharge.service.CardVoucherService;
import com.recharge.service.GoodsProviderService;
import com.recharge.service.GoodsService;
import com.recharge.service.ProviderService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 卡密表 服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2020-10-20
 */
@Service
public class CardVoucherServiceImpl extends ServiceImpl<CardVoucherMapper, CardVoucherEntity> implements CardVoucherService {


    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private ProviderService providerService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsProviderService goodsProviderService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisUtil redisUtil;

    private volatile List<CardVoucherEntity> cardCacheList = new ArrayList<>();

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO add(CardVoucherDO domain) {

        CardVoucherEntity entity = new CardVoucherEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        //将卡的面值转换成厘
        entity.setDenomination(entity.getDenomination()*1000);
        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setModifier(entity.getCreator());


        boolean res = false;
        try {
            res = this.save(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_ADD_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_ADD_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(CardVoucherDO domain) {

        CardVoucherEntity entity = new CardVoucherEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());
        //将充值卡面值做转换成厘
        entity.setDenomination(entity.getDenomination()*1000);
        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断res的值是true.如果不是 就代表更新失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        CardVoucherEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        CardVoucherDO domain = getDomain(entity);
        //排除数学运算异常
        if(domain.getDenomination()!=null&&domain.getDenomination()>0){
            //将面值转换成元
            domain.setDenomination(domain.getDenomination()/1000);
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO remove(String id, String modifier) {
        ResultDO result = new ResultSupport();

        CardVoucherEntity entity = new CardVoucherEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断res的值是true.如果不是 就代表删除失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_DELETE_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultDO find(CardVoucherQueryDO query) {
        ResultDO result = new ResultSupport();

        Page<CardVoucherEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        IPage<CardVoucherEntity> iPage = null;
        QueryWrapper<CardVoucherEntity> queryWrapper = new QueryWrapper<>();
        //过滤已经逻辑删除的充值卡
        queryWrapper.lambda().eq(CardVoucherEntity::getIsDelete,Constant.IS_DELETE_FALSE);
        //根据充值卡号
        if(StringUtils.isNotEmpty(query.getVoucherNo())){
            queryWrapper.lambda().eq(CardVoucherEntity::getVoucherNo,query.getVoucherNo());
        }
        //根据状态
        if (query.getStatus()!=null&&query.getStatus()!=0){
            queryWrapper.lambda().eq(CardVoucherEntity::getStatus,query.getStatus());
        }
        //根据供应商
        if(StringUtils.isNotEmpty(query.getProviderNo())){
            queryWrapper.lambda().eq(CardVoucherEntity::getProviderNo,query.getProviderNo());
        }
        //根据商品面值
        if(query.getDenomination()!=null&&query.getDenomination()!=0){
            queryWrapper.lambda().eq(CardVoucherEntity::getDenomination,query.getDenomination()*1000);
        }
        //根据商品编号
        if((query.getGoodsNo()!=null)){
            queryWrapper.lambda().eq(CardVoucherEntity::getGoodsNo,query.getGoodsNo());
        }
        //根据修改的日期排序
        queryWrapper.lambda().orderByDesc(CardVoucherEntity::getModifiDate);
        try{
            iPage = baseMapper.selectPage(page, queryWrapper);
        }catch (Exception e){
           //异常代码块
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：数据库查询异常" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //正常返回
        List<CardVoucherEntity> cardVoucherEntityList = iPage.getRecords();
        List<CardVoucherDO> list = null;
        if(cardVoucherEntityList.size()>0&&cardVoucherEntityList!=null){
            list = this.getDomainList(cardVoucherEntityList);
            //根据充值卡的providerId(供应商id)查寻供应商名称
            for (CardVoucherDO cardVoucherDO:list) {
                String providerId =  cardVoucherDO.getProviderId();
                ResultDO resultDO = providerService.get(providerId);
                ProviderDO providerDO = (ProviderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
                //将查询处理的供应商名字设置到cardVoucherEntity
                if(providerDO!=null){
                    cardVoucherDO.setProviderName(providerDO.getProviderName());
                }
                //将查询的商品名称设置到cardVoucherEntity
                String goodsName = this.getGoodsNameByGoodsNo(cardVoucherDO.getGoodsNo());
                cardVoucherDO.setGoodsName(goodsName);
            }
            for (CardVoucherDO cardVoucherDO:list) {
                //排除数学运算异常
                if(cardVoucherDO.getDenomination()==null||cardVoucherDO.getDenomination()<=0)continue;
                cardVoucherDO.setDenomination(cardVoucherDO.getDenomination()/1000);

            }
        }
        PageDO<CardVoucherDO> pageDO = new PageDO<>();
        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(list);
        result.setModel(ResultDO.FIRST_MODEL_KEY,pageDO);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO insertAll(List<CardVoucherDO> cardVoucherDOList) {
        ResultSupport result = new ResultSupport();

        List<CardVoucherEntity> cardVoucherEntityList= new ArrayList<>();

        if(cardVoucherDOList==null||cardVoucherDOList.size()<=0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            return result;
        }
        for(CardVoucherDO cardVoucherDO:cardVoucherDOList){
            CardVoucherEntity cardVoucherEntity = new CardVoucherEntity();
            result = BeanUtilsExtends.copy(cardVoucherEntity, cardVoucherDO);
            if (!result.isSuccess()) {
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                return result;
            }
            cardVoucherEntity.setCreateDate(Calendar.getInstance().getTime());
            cardVoucherEntity.setModifier(cardVoucherEntity.getCreator());
            if(cardVoucherEntity.getDenomination()==null||cardVoucherEntity.getDenomination()<=0){
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
                logger.debug("error code：充值卡面值不能<=0" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
                return result;
            }
            cardVoucherEntity.setDenomination(cardVoucherEntity.getDenomination()*1000);
            cardVoucherEntity.setModifiDate(cardVoucherEntity.getCreateDate());
            //批量添加默认状态有效
            cardVoucherEntity.setStatus(1);
            cardVoucherEntityList.add(cardVoucherEntity);
        }
        if(cardVoucherEntityList==null&&cardVoucherEntityList.size()<=0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            logger.debug("error code：数据拷贝失败" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            return result;
        }
        boolean res = false;
        try {
            //数据插入数据库
            res = this.saveBatch(cardVoucherEntityList);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            return result;
        }
        //判断res的值是true.如果不是 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
        }
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO removeList(String[] cardVoucherIds, String modifier) {
        ResultDO result = new ResultSupport();
        if(cardVoucherIds==null&&cardVoucherIds.length==0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_LIST_ERROR.getCode() + " msg" + ErrorCode.PARAM_LIST_ERROR.getMsg());
            return result;
        }
        for(String item: cardVoucherIds){
            result = this.remove(item, modifier);
            if(!result.isSuccess()){
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.GOODS_DELETE_ERROR);
                logger.debug("error code：" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.GOODS_DELETE_ERROR.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return result;
    }


    public ResultDO editStatus(CardVoucherDO domain) {
        logger.info("核销卡号为:" + domain.getVoucherNo() + ": 该卡的状态为:" + domain);

        CardVoucherEntity entity = new CardVoucherEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        boolean res = false;
        entity.setId(domain.getId());
        try {
            res = this.save(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_ADD_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_ADD_ERROR.getMsg());
            return result;
        }
        return result;
    }

    public ResultDO editStatus(String cardNo, Integer status) {
        logger.debug("核销卡号为:" + cardNo + ": 该卡的状态为:" + status);
        ResultDO result = new ResultSupport();
        CardVoucherEntity entity = null;
        try {
            entity = this.baseMapper.selectOne(Wrappers.<CardVoucherEntity>lambdaQuery().eq(CardVoucherEntity::getVoucherNo, cardNo));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        if(entity == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            return result;
        }
        CardVoucherEntity updateEntity = new CardVoucherEntity();
        updateEntity.setId(entity.getId());
        updateEntity.setStatus(status);

        boolean res = false;
        try {
            res = this.updateById(updateEntity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断res的值是true.如果不是 就代表删除失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getMsg());
        }

        entity.setStatus(status);
        CardVoucherDO cardVoucherDO = getDomain(entity);
        result.setModel(ResultDO.FIRST_MODEL_KEY, cardVoucherDO);
        return result;
    }

    public ResultDO cardCallback(CardVoucherDO cardVoucher) {
        ResultDO result = new ResultSupport();
        String callbackUrl = (String) redisUtil.get(Constant.PROVIDER_CARD + ":" + cardVoucher.getProviderId());
        if(callbackUrl == null) {
            result.setModel(ResultDO.FIRST_MODEL_KEY, "fail");
            return result;
        }
        Gson gson = new Gson();
        CardCallbackDO domain = new CardCallbackDO();
        domain.setCardNo(cardVoucher.getVoucherNo());
        domain.setStatus(cardVoucher.getStatus());
        String jsonData = gson.toJson(domain);
        String responseData = null;
        logger.debug("发送代理商回调:" + callbackUrl + ":" + jsonData);
        try {
            responseData = HttpUtil.post(callbackUrl, jsonData, conn -> {
                        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                        conn.setRequestProperty("accept", "application/json;charset=utf-8");
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.warn("发送下游回调" + jsonData + "回调下游接口返回结果为：" + responseData);
        responseData = responseData == null ? "" : responseData;

        /*try {
            this.removeById(cardVoucher.getId());
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }*/
        result.setModel(ResultDO.FIRST_MODEL_KEY, responseData);
        return result;
    }


    public ResultDO getCardByGoodsNo(Integer goodsNo) {

        ResultDO result = new ResultSupport();

        Page<CardVoucherEntity> page = new Page<>(0, 100);
        IPage<CardVoucherEntity> iPage = null;
        CardVoucherEntity entity = null;
        String lockKey = "LOCK_COURSE" + goodsNo;
        RLock lock = redissonClient.getLock(lockKey);
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                if(cardCacheList.size() == 0) {
                    iPage = this.baseMapper.selectPage(page, Wrappers.<CardVoucherEntity>lambdaQuery()
                            .eq(CardVoucherEntity::getGoodsNo, goodsNo)
                            .eq(CardVoucherEntity::getStatus, Constant.CARDVOUCH_STATUS_VALID));

                    if (iPage.getRecords().size() == 0) {
                        result.setSuccess(false);
                        logger.debug("获取卡密失败 error code : " + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
                        result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
                        return result;
                    }
                    cardCacheList = iPage.getRecords();
                }
                int index = 0;
                if(cardCacheList.size() > 1) {
                    Random random = new Random();
                    index = random.nextInt(cardCacheList.size());
                }
                entity = cardCacheList.get(index);
                cardCacheList.remove(index);
                this.baseMapper.deleteById(entity.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            logger.debug("获取卡密失败 error code : " + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            return result;
        } finally {
            if(lock != null) {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

        CardVoucherDO domain = getDomain(entity);
        //只需要返回一条数据放入  ResultDO.FIRST_MODEL_KEY
        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.SUPPORTS)
    public ResultDO queryCardByGoodsNo(CardVoucherQueryDO query) {
        ResultDO result = new ResultSupport();
        IPage<CardVoucherEntity> iPage = null;
        List<CardVoucherEntity> list = null;
        if(query==null) return  null;
        //添加分页插件
        Page<CardVoucherEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        QueryWrapper<CardVoucherEntity> queryWrapper = new QueryWrapper<>();
        //过滤已经逻辑删除的充值卡
        queryWrapper.lambda().eq(CardVoucherEntity::getIsDelete,Constant.IS_DELETE_FALSE)
                .eq(CardVoucherEntity::getGoodsNo,query.getGoodsNo());
        try{
            iPage = this.baseMapper.selectPage(page, queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            logger.debug("获取卡密失败 error code : " + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            return result;
        }

        List<CardVoucherEntity> cardVoucherEntityList = iPage.getRecords();
        List<CardVoucherDO> cardVoucherDOList = this.getDomainList(cardVoucherEntityList);
        //判断数据复制是否成功
        if(cardVoucherDOList.size() == 0||cardVoucherDOList==null) {
            result.setSuccess(false);
            logger.debug("获取卡密失败 error code : " + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            return result;
        }
        //正常返回
        result.setModel(ResultDO.FIRST_MODEL_KEY,cardVoucherDOList);

        return result;
    }

    private CardVoucherDO getDomain(CardVoucherEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        CardVoucherDO domain = new CardVoucherDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<CardVoucherDO> getDomainList(List<CardVoucherEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<CardVoucherDO> doList = new ArrayList<CardVoucherDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(CardVoucherEntity entity : list) {

                CardVoucherDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
    //根据商品编号查商品名称
    @Override
    public String getGoodsNameByGoodsNo(Integer goodsNo){
        //判断传入的字符串
        if(goodsNo!=null&&goodsNo!=0){
            String goodsNameByGoodsNo = baseMapper.getGoodsNameByGoodsNo(goodsNo);
            return goodsNameByGoodsNo;
        }

        return null;
    }
    //excel表格批量导入
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO getExcel(MultipartFile file,GoodsDO goodsDO) {
        ResultDO result = new ResultSupport();
        List<CardVoucherDO> list = new ArrayList<CardVoucherDO>();
        InputStream is = null;
        if(null==file) return null;
        try{
            String fileName = file.getOriginalFilename();
            Workbook workbook = null;

            is = file.getInputStream();
            if (fileName.endsWith("xls")) {
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(is);
            }else{
                result.setSuccess(false);
                logger.debug("文件格式不对rror code : " + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getMsg());
                result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR);
                return result;
            }
            //判断excel表格是否创建成功
            if(workbook!=null){
                for(int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++){
                    Sheet sheet = workbook.getSheetAt(sheetNum);//依次读取每一个sheet页
                    if (sheet == null) {//判断当前的sheet页有没有数据
                        continue;//如果没有，则跳过当前的循环，进入下次循环
                    }
                    int firstRowNum = sheet.getFirstRowNum();//读取第一次出现数据的下标（从哪一行开始有数据）
                    int lastRowNum = sheet.getLastRowNum();//读取最后一条数据的下标（没有数据的那一行）
                    //遍历excel每一行 表头去掉
                    for (int j = firstRowNum+1; j <= lastRowNum; j++) {
                        Row row = sheet.getRow(j);
                        if (row == null) {
                            continue;
                        }
                        //这里new 一个对象，用来装填从页面上传的Excel数据，字段根据上传的excel决定
                        CardVoucherDO cardVoucherDO = new CardVoucherDO();
                        //循环一行数据取出对应的cell
                        Cell ce1 = row.getCell(0);
                        Cell ce2 = row.getCell(1);
                        if(ce1==null||ce2==null){
                            result.setSuccess(false);
                            logger.debug("字段有空值，插入失败 error code : " + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getMsg());
                            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR);
                            return result;
                        }
                        //将excel的列数据统一转换成字符串处理
                        row.getCell(0).setCellType(CellType.STRING);
                        row.getCell(1).setCellType(CellType.STRING);
                        //排除""空串
                        if(ce1.getStringCellValue().equals("")||ce2.getStringCellValue().equals("")){
                            result.setSuccess(false);
                            logger.debug("字段有空字符串，插入失败 error code : " + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getMsg());
                            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR);
                            return result;
                        }
                        cardVoucherDO.setGoodsNo(goodsDO.getGoodsNo());
                        cardVoucherDO.setDenomination(goodsDO.getDenomination());
                        cardVoucherDO.setVoucherNo(ce1.getStringCellValue());
                        cardVoucherDO.setVoucherPassword(ce2.getStringCellValue());
                        list.add(cardVoucherDO);
                    }
                }

            }
        }catch (Exception e){
            //异常代码块
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            logger.debug("error code：网络异常 " + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            return result;
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
                    logger.debug("error code：获取输入流异常" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
                    return result;
                }
            }
        }
        //判断excel是否封装的list
        if(list.size() == 0||list==null) {
            result.setSuccess(false);
            logger.debug("导入了一个空集合，失败 error code : " + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            return result;
        }
        long startTime = System.currentTimeMillis();
        result = insertAll(list);
        long endTime = System.currentTimeMillis();
        logger.debug("批量导入充值卡执行时间="+(endTime-startTime));
        if(!result.isSuccess()){
            result.setSuccess(false);
            logger.debug("批量导入充值卡失败 error code : " + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_LIST_CARD_VOUCHER_ERROR);
            return result;
        }
        return result;
    }

    @Override
    public ResultDO findList(CardVoucherQueryDO query) {
        ResultDO result = new ResultSupport();

        Page<CardVoucherEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        List<CardVoucherEntity> dataList = null;
        QueryWrapper<CardVoucherEntity> queryWrapper = new QueryWrapper<>();
        //过滤已经逻辑删除的充值卡
        queryWrapper.lambda().eq(CardVoucherEntity::getIsDelete,Constant.IS_DELETE_FALSE);
        //根据充值卡号
        if(StringUtils.isNotEmpty(query.getVoucherNo())){
            queryWrapper.lambda().eq(CardVoucherEntity::getVoucherNo,query.getVoucherNo());
        }
        //根据状态
        if (query.getStatus()!=null&&query.getStatus()!=0){
            queryWrapper.lambda().eq(CardVoucherEntity::getStatus,query.getStatus());
        }
        //根据供应商
        if(StringUtils.isNotEmpty(query.getProviderNo())){
            queryWrapper.lambda().eq(CardVoucherEntity::getProviderNo,query.getProviderNo());
        }
        //根据商品面值
        if(query.getDenomination()!=null&&query.getDenomination()!=0){
            queryWrapper.lambda().eq(CardVoucherEntity::getDenomination,query.getDenomination()*1000);
        }
        //根据商品编号
        if((query.getGoodsNo()!=null)){
            queryWrapper.lambda().eq(CardVoucherEntity::getGoodsNo,query.getGoodsNo());
        }
        //根据修改的日期排序
        queryWrapper.lambda().orderByDesc(CardVoucherEntity::getModifiDate);
        try{
            dataList = baseMapper.selectList(queryWrapper);
        }catch (Exception e){
            //异常代码块
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：数据库查询异常" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //正常返回
        List<CardVoucherDO> list = null;
        if(dataList.size()>0&&dataList!=null){
            list = this.getDomainList(dataList);
            //根据充值卡的providerId(供应商id)查寻供应商名称
            for (CardVoucherDO cardVoucherDO:list) {
                String providerId =  cardVoucherDO.getProviderId();
                ResultDO resultDO = providerService.get(providerId);
                ProviderDO providerDO = (ProviderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
                //将查询处理的供应商名字设置到cardVoucherEntity
                if(providerDO!=null){
                    cardVoucherDO.setProviderName(providerDO.getProviderName());
                }
                //将查询的商品名称设置到cardVoucherEntity
                String goodsName = this.getGoodsNameByGoodsNo(cardVoucherDO.getGoodsNo());
                cardVoucherDO.setGoodsName(goodsName);
            }
            for (CardVoucherDO cardVoucherDO:list) {
                //排除数学运算异常
                if(cardVoucherDO.getDenomination()==null||cardVoucherDO.getDenomination()<=0)continue;
                cardVoucherDO.setDenomination(cardVoucherDO.getDenomination()/1000);

            }
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY,list);
        return result;
    }


}
